import axios from 'axios'
import { ElLoading } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

// 配置默认基本api
let loading: ILoadingInstance
axios.defaults.baseURL = 'http://apis.imooc.com/api'
axios.interceptors.request.use(config => {
  if (!config.params?.__nocover) {
    loading = ElLoading.service()
  }
  config.params = { ...config.params, icode: '1FC17F5781FD38E1' }
  config.data = { ...config.data, icode: '1FC17F5781FD38E1' }
  return config
})

axios.interceptors.response.use(res => {
  if (loading) loading.close()
  if (res.data.code) {
    return Promise.reject<ErrorProp>(res.data)
  }
  return res.data
}, err => {
  console.error('请求错误', err)
  if (loading) loading.close()
  const errorRes = err.response.data
  if (errorRes.error) {
    const resp: ErrorProp = {
      code: errorRes.code,
      msg: errorRes.error
    }
    return Promise.reject<ErrorProp>(resp)
  }
  return err
})

export default axios
